package business_service;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

public class ServerFileHelper implements Runnable{
	Socket		sock;
	Protocol.utility.NetAddress	netAddress;
	String 		filePath;
	
	DataInputStream	fin= null ;
	DataOutputStream fou = null ;
	
	public ServerFileHelper(Protocol.utility.NetAddress neta, String filep) {
		this.netAddress = neta;
		this.filePath = filep;
	}
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
		try {
			sock  = new Socket(netAddress.getIp(), netAddress.getPort());
		} catch (UnknownHostException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		if(netAddress.getPort() == 6868){
			doReceive();
		}
		else if(netAddress.getPort() == 6869) {
			doSend();
		}
	}
	private void startDataTrans() {
		byte[]   buffer = new byte[1024];
		int len=0;
		do{
			try {
				len = fin.read(buffer, 0, 1024);
				if(len != -1)  {
					fou.write(buffer, 0, len);
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		} while(len != -1);
		
		try {
			fin.close();
			fou.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	private void doSend() {
		try {
			fou= new DataOutputStream(sock.getOutputStream());
			fin = new DataInputStream(new FileInputStream(new File(filePath)));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	
		startDataTrans();
			
	}
	private void doReceive() {
		try {
			fou=  new DataOutputStream(new FileOutputStream(new File(filePath)));
			fin = new DataInputStream(sock.getInputStream());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		startDataTrans();
		
	}
}
